from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.views import View
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django import http
from meiduo.meiduo_mall.meiduo_mall.utils.response_code import RETCODE
import logging
from django.contrib.auth import login
from oauth.models import OAuthQQUser
from . import utils
import re
from django_redis import get_redis_connection
from users.models import User
logger = logging.getLogger("django")


# 处理用户登录后的回调
class QQAuthUserView(View):
    def get(self, request):
        code = request.GET.get("code")
        if code is None:
            return http.HttpResponseForbidden("获取code失败")
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)
        try:
            access_token = oauth.get_access_token(code)  # 获取access_token
            openid = oauth.get_open_id(access_token)  # 获取openid

            qquser = OAuthQQUser.objects.get(openid=openid)
            if qquser is None:
                # 显示绑定页面
                context = {"access_token_openid": utils.encryopenid(openid)}
                return render(request, 'oauth_callback', context)
                pass
            else:
                # 已绑定
                login(request, qquser.user)  # 登录，状态保持
                state = request.GET.get('state')
                response = redirect(state)  # 从哪来回哪去
                response.set_cookie("username", qquser.user.username, 60 * 30)
                return
        except Exception as e:
            logger.error(e)
            return http.HttpResponseServerError("OAuth2.0认证失败")
        pass

    def post(self, request):  # 绑定用户
        # 接收参数
        mobile = request.POST.get('mobile')
        pwd = request.POST.get('password')
        sms_code_client = request.POST.get('sms_code')
        access_token = request.POST.get('access_token')

        # 校验参数
        # 判断参数是否齐全
        if not all([mobile, pwd, sms_code_client]):
            return http.HttpResponseForbidden('缺少必传参数')
        # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('请输入正确的手机号码')
        # 判断密码是否合格
        if not re.match(r'^[0-9A-Za-z]{5,20}$', pwd):
            return http.HttpResponseForbidden('请输入8-20位的密码')
        # 判断短信验证码是否一致
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)
        if sms_code_server is None:
            return render(request, 'oauth_callback.html', {'sms_code_errmsg': '无效的短信验证码'})
        if sms_code_client != sms_code_server.decode():
            return render(request, 'oauth_callback.html', {'sms_code_errmsg': '输入短信验证码有误'})
        # 校验openid
        openid = utils.checkopenid(access_token)
        if not openid:
            return render(request, 'oauth_callback.html', {"openid_errmsg": 'openid无效'})
        # 校验手机号是否已注册
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 用户不存在，则注册一个
            user = User.objects.create_user(username=mobile, password=pwd, mobile=mobile)
        else:
            # 用户已存在则校验密码
            if not user.check_password(pwd):
                return render(request, "oauth_callback.html", {"account_errmsg": "账号或密码错误"})
        # 将用户与openid绑定
        try:
            qquser = OAuthQQUser.objects.create(user=user, openid=openid)
        except Exception as e:
            logger.error(e)
            return render(request, "oauth_callback.html", {"qq_login_errmsg": "openid绑定失败"})

        login(request, qquser.user)
        # 重定向到state
        state = request.GET.get("state")
        response = redirect(state)
        response.set_cookie("username", qquser.user.username, 60*30)
        return response


# 获取qq登录页面
class QQLoginView(View):
    def get(self, request):
        next = request.GET.get("next")
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state=next)
        url = oauth.get_qq_url()  # 获取qq登录扫码页面
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': "ok", 'login_url': url})
